package com.wanmao.test.util;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

	public static String encrypt(String content, String keyseed)
			throws Exception {
		SecretKeySpec key = getKeySpecFromBytes(keyseed.toUpperCase());
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(1, key);
		byte[] byteEnc = cipher.doFinal(content.getBytes("UTF-8"));
		return byte2hex(byteEnc);
	}

	public static String decrypt(String content, String keyseed)
			throws Exception {
		SecretKeySpec key = getKeySpecFromBytes(keyseed.toUpperCase());
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(2, key);
		String result = new String(cipher.doFinal(hex2byte(content
				.getBytes("UTF-8"))));

		return result.trim();
	}


	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; ++n) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}


	private static byte[] hex2byte(byte[] b) {
		if (b.length % 2 != 0)
			throw new IllegalArgumentException("长度不是偶数!");

		byte[] b2 = new byte[b.length / 2];

		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[(n / 2)] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	private static SecretKeySpec getKeySpecFromBytes(String strBytes)
			throws NoSuchAlgorithmException {
		SecretKeySpec spec = new SecretKeySpec(hex2byte(strBytes.getBytes()),
				"AES");

		return spec;
	}

	public static byte[] initSecretKey() {

	       KeyGenerator kg = null;
	       try {
	           kg = KeyGenerator.getInstance("AES");
	       } catch (NoSuchAlgorithmException e) {
	           e.printStackTrace();
	           return new byte[0];
	       }

	       kg.init(128);

	       SecretKey  secretKey = kg.generateKey();
	       return secretKey.getEncoded();
	   }
	
	public static void main(String[] args) throws Exception{    
		byte[] k = initSecretKey();
		System.out.println(byte2hex(k));
		System.out.println("encypt加密:"+encrypt("12asdfasdfas3", "C3D03E9948AEAB8B7CD1ED771CB0CB9D"));
		System.out.println("encypt解密:"+decrypt("672D6F7B846588380A01B500A0C1C0FE", "C3D03E9948AEAB8B7CD1ED771CB0CB9D"));
		
	}
}
